package com.example.logintest1.serviceimpl.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.logintest1.Entry.AdminMember;
import com.example.logintest1.Entry.LoginUser;
import com.example.logintest1.mapper.AdminMemberMapper;
import com.example.logintest1.mapper.MenuMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.management.relation.Role;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private AdminMemberMapper userMapper;
    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String user) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<AdminMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminMember::getUser,user);
        AdminMember adminMember = userMapper.selectOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(adminMember)){
            throw new RuntimeException("用户名或密码错误");
        }

        String userName = adminMember.getUser();
        String password = adminMember.getPas();

        // 3.登录成功填充用户菜单数据权限返回
        Set<String> permissions = new HashSet<>();
        permissions.add("system:dept:index");
        Set<Role> roles = new HashSet<>();
        return new LoginUser(1L ,userName, password, permissions, roles);
    }
}